import cryptoJs from "crypto-js";
import jsMd5 from "js-md5";
import base64 from "js-base64";

// 接口数据加密函数
export function encrypt(str, key, iv) {
	var key2 = cryptoJs.enc.Utf8.parse(key);
	var iv2 = cryptoJs.enc.Utf8.parse(iv);
	var encrypted = cryptoJs.AES.encrypt(str, key2, {
		iv: iv2,
		mode: cryptoJs.mode.CBC,
		padding: cryptoJs.pad.Pkcs7
	});
	return encrypted.toString();
}
// 解密函数
export function decrypt(str, key, iv) {
	var key2 = cryptoJs.enc.Utf8.parse(key);
	var iv2 = cryptoJs.enc.Utf8.parse(iv);
	var decrypted = cryptoJs.AES.decrypt(str, key2, {
		iv: iv2,
		padding: cryptoJs.pad.Pkcs7
	});
	return JSON.parse(decrypted.toString(cryptoJs.enc.Utf8));
}
//生成随机数
export function _getRandomString(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
	var maxPos = chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}
  export function sign(data, appKey) {
    // 参数排序
    data = sortObj(data)
    // 临时字符串
    const tempString = serializeObject(data)
	// console.log('----------',tempString);
    // 加密
    // return jsMd5(base64.encode(`${appKey}${tempString}${appKey}`)).toLowerCase();
	// console.log(jsMd5(tempString + appKey));
    return jsMd5(tempString + appKey);
  }

  export function  sortObj(data) {
    const keysArr = Object.keys(data).sort();
    
    for (const i in keysArr) {
      sortObj[keysArr[i]] = data[keysArr[i]];
    }
    return sortObj;
  }
  
  export function serializeObject(data) {
      const str = [];
      for (const k in data) {
        if (Object.hasOwnProperty.call(data, k)) {
          str.push(k + "=" + encodeURIComponent(data[k]));
        }
      }
      return str.join("&");
    }